//8位输入优先编码器设计

//优先编码器
module priority_encoder8(
    input wire[7:0] in,
    output wire[2:0] out,
    output reg valid
);

reg[2:0] tmp_out;

always @(*) begin
    //valid信号表示是否是有效输入
    valid = 0; //默认值为0 只有下面八种情况为有效输入
    tmp_out = 3'b000;

    casez(in) 
        8'b1zzzzzzz: begin tmp_out = 3'b111; valid = 1;end
        8'b01zzzzzz: begin tmp_out = 3'b110; valid = 1;end
        8'b001zzzzz: begin tmp_out = 3'b101; valid = 1;end
        8'b0001zzzz: begin tmp_out = 3'b100; valid = 1;end
        8'b00001zzz: begin tmp_out = 3'b011; valid = 1;end
        8'b000001zz: begin tmp_out = 3'b010; valid = 1;end
        8'b0000001z: begin tmp_out = 3'b001; valid = 1;end
        8'b00000001: begin tmp_out = 3'b000; valid = 1;end

        default: begin tmp_out = 3'b000; valid = 0; end
    endcase

end

    assign out = tmp_out;
endmodule




//测试文件 testbench of priority_encoder8
`timescale 1ns/100ps
module priority_encoder8_tb;
    //存储
    reg[7:0] in;
    //由驱动信号产生 因此用wire类型
    wire valid;
    wire [2:0] out;

    priority_encoder8 priority_encoder8(
        .in(in),
        .out(out),
        .valid(valid)
    );

    initial begin
        in = 8'b00000000;  //无效输入
    #10 in = 8'b00000001;
    #10 in = 8'b00001000;
    #10 in = 8'b10000000;
    #10 $stop;
    end

endmodule